package com.zw.mizhe;

import android.app.Application;
import android.os.Build;
import android.widget.Toast;

import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.zw.mizhe.bean.base.BaseDataEntity;
import com.zw.mizhe.common.net.NetChangeObserver;
import com.zw.mizhe.common.net.NetWorkUtil;
import com.zw.mizhe.common.net.NetworkStateReceiver;
import com.zw.mizhe.common.utils.AppActivityLifecycleCallbacks;

public class App extends Application {
    private static App app;
    private AppActivityLifecycleCallbacks callbacks;

    public BaseDataEntity entity;

    private NetChangeObserver observer = new NetChangeObserver() {

        @Override
        public void onConnect(NetWorkUtil.NetType type) {
            super.onConnect(type);
            Toast.makeText(App.this, "网络已连接", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onDisConnect() {
            super.onDisConnect();
            Toast.makeText(App.this, "网络已断开", Toast.LENGTH_SHORT).show();
        }
    };

    //内存泄露检测
    private  RefWatcher refWatcher;


    @Override
    public void onCreate() {
        super.onCreate();
        app = this;

        //检测内存泄露
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return;
        }
        refWatcher = LeakCanary.install(this);

        registerActivityLifecycleCallbacks();
    }

    public static App getInstance() {
        return app;
    }

    /**
     * 监听网络变化
     */
    private void registerActivityLifecycleCallbacks() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && callbacks == null)
            callbacks
                    = new AppActivityLifecycleCallbacks();
        //监听activity的生命周期
        registerActivityLifecycleCallbacks(callbacks);
        //监听网络变化
        registerNetworkStateReceiver();

    }

    public void unRegisterActivityLifecycleCallbacks() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && callbacks != null) {
            unregisterActivityLifecycleCallbacks(callbacks);
        }
    }

    private void registerNetworkStateReceiver() {
        NetworkStateReceiver.registerNetworkStateReceiver(this);
        NetworkStateReceiver.registerObserver(observer);
    }

    public void unRegisterNetworkStateReceiver() {
        if (observer != null) {
            NetworkStateReceiver.removeRegisterObserver(observer);
        }
        NetworkStateReceiver.unRegisterNetworkStateReceiver(this);
    }

    public RefWatcher getRefWatcher() {
        return refWatcher;
    }
}
